;void function(exportsName, strUndef){

var Global = require('global');
var doc = Global.document;
var body = doc.body;
var support = 'postMessage' in Global;

var Client = function(serverUrl, debug){
	if(!support){
		throw "NOT SUPPORT `postMessage` method!";
	}
	
	this.server = null;
	this.callbacks = {};
	
	if(debug){
		var ver = "debug=" + new Date().valueOf();
		var rsearch = /\?[^#]*/
		var rhash = /#.*/;
		var search = serverUrl.match(rsearch);
		var hash = serverUrl.match(rhash);
		var preurl = serverUrl.replace(rsearch, '').replace(rhash, '');
		
		this.serverUrl = preurl
			+ (search ? search[0] + ('&' + ver) : ('?' + ver))
			+ (hash ? hash[0] : '');
	}else{
		this.serverUrl = serverUrl;
	}
	
	this.create();
};

Client.prototype = {
	create: function(){
		var _this = this;
		
		var serverFrame = doc.createElement('iframe');
		serverFrame.frameborder = 0;
		serverFrame.width = 1;
		serverFrame.height = 1;
		serverFrame.style.cssText = 'width:1px; height:1px; position:absolute; top:0; right:0';
		serverFrame.src = this.serverUrl;
		
		body.appendChild(serverFrame);
		this.serverFrame = serverFrame;
		this.server = serverFrame.contentWindow;
		
		// 回调事件
		this.__msgHandle = function(e){
			_this._msgHandle(e);
		};
		
		Global.addEventListener('message', this.__msgHandle, false);
	},
	dispose: function(){
		this.server = null;
		Global.removeEventListener('message', this.__msgHandle);
		this.serverFrame.src = '';
		doc.removeChild(this.serverFrame);
		this.serverFrame = null;
	},
	// 消息回调
	_msgHandle: function(e){
		var _this = this;
		
		if(e.data){
			try{
				var data = JSON.parse(e.data);
			
				if(data.server === _this.serverUrl){
					var callbacks = _this.callbacks[data.src];
					
					callbacks && callbacks.length && callbacks.forEach(function(callback){
						(typeof callback === 'function') && callback(data.script);
					});
					
					_this.callbacks[data.src] = [];
				}
			}catch(ex){}
		}
	},
	// 获取脚本代码
	get: function(src, callback){
		if(!this.callbacks[src]){
			this.callbacks[src] = [];
		}
		
		this.callbacks[src].push(callback);
		
		this.server.postMessage(JSON.stringify({
			src: src,
			client: Global.location.href,
			stamp: new Date().valueOf()
		}), '*');
	}
};


// 导出
if(typeof define === 'function'){
	define(function(){
		return Client;
	});
}else if(typeof module !== strUndef && 'exports' in module){
	module.exports = Client;
}else{
	Global[exportsName] = Client;
}

}.call(this, 'XScriptClient', typeof undefined);